using WebApplication1.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using WebApplication1.Utils;

// 创建WebApplication构建器实例，用于配置应用程序的服务和中间件
var builder = WebApplication.CreateBuilder(args);

// 向依赖注入容器中添加服务

// 配置数据库连接
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<BookDbContext>(options =>
    options.UseMySql(connectionString, MySqlServerVersion.AutoDetect(connectionString)));

// 添加MVC控制器服务，使应用程序能够处理HTTP请求
builder.Services.AddControllers();
// 添加API Explorer服务，用于生成API文档
builder.Services.AddEndpointsApiExplorer();
// 添加Swagger生成器服务，用于生成OpenAPI规范文档
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new Microsoft.OpenApi.Models.OpenApiSecurityScheme
            {
                Reference = new Microsoft.OpenApi.Models.OpenApiReference
                {
                    Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});
// 添加JWT认证服务
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = JwtHelper.GetValidationParameters();
});

// 构建WebApplication实例
var app = builder.Build();

// 配置HTTP请求处理管道
// 检查是否处于开发环境
if (app.Environment.IsDevelopment())
{
    // 启用Swagger中间件，用于生成OpenAPI文档
    app.UseSwagger();
    // 启用SwaggerUI中间件，提供API文档的Web界面
    app.UseSwaggerUI();
}

// 启用HTTPS重定向中间件，将HTTP请求重定向到HTTPS
app.UseHttpsRedirection();

// 启用身份认证中间件
app.UseAuthentication();

// 启用授权中间件
app.UseAuthorization();

// 添加控制器路由映射，将请求路由到对应的控制器动作方法
app.MapControllers();

// 启动应用程序，开始监听HTTP请求
app.Run();
